<template>
  <div class="feedback-container">
    <!-- 筛选条件 -->
    <el-card class="filter-card" shadow="hover">
      <div class="filter-header">
        <h3>反馈筛选</h3>
        <div class="filter-actions">
          <el-button type="success" plain size="small" @click="exportFeedback">
            <el-icon><Download /></el-icon>导出数据
          </el-button>
          <el-button type="primary" plain size="small" @click="applyFilters">
            <el-icon><Search /></el-icon>应用筛选
          </el-button>
        </div>
      </div>
      <div class="filter-content">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-select v-model="urgencyLevel" placeholder="紧急程度" clearable style="width: 100%">
              <el-option label="全部" value="" />
              <el-option label="紧急" value="high">
                <el-tag type="danger" size="small">紧急</el-tag>
              </el-option>
              <el-option label="中等" value="medium">
                <el-tag type="warning" size="small">中等</el-tag>
              </el-option>
              <el-option label="普通" value="low">
                <el-tag type="info" size="small">普通</el-tag>
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select v-model="feedbackType" placeholder="反馈类型" clearable style="width: 100%">
              <el-option label="全部" value="" />
              <el-option label="系统问题" value="system" />
              <el-option label="内容建议" value="content" />
              <el-option label="操作问题" value="operation" />
              <el-option label="设备问题" value="device" />
              <el-option label="其他" value="other" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select v-model="status" placeholder="处理状态" clearable style="width: 100%">
              <el-option label="全部" value="" />
              <el-option label="待处理" value="pending" />
              <el-option label="处理中" value="processing" />
              <el-option label="已解决" value="resolved" />
              <el-option label="已关闭" value="closed" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY/MM/DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 反馈列表 -->
    <el-card shadow="hover" class="feedback-list-card">
      <template #header>
        <div class="card-header">
          <span>反馈列表</span>
          <br>
          <el-radio-group v-model="viewMode" size="small">
            <el-radio-button label="all">全部</el-radio-button>
            <el-radio-button label="pending">待处理</el-radio-button>
            <el-radio-button label="resolved">已解决</el-radio-button>
          </el-radio-group>
        </div>
      </template>

      <el-table
        :data="feedbackTableData"
        style="width: 100%"
        border
        stripe
        v-loading="loading"
      >
        <el-table-column prop="feedbackId" label="ID" width="80" />
        <el-table-column prop="userId" label="用户ID" width="100" />
        <!-- <el-table-column prop="userName" label="用户姓名" width="120" /> -->
        <el-table-column prop="feedbackType" label="反馈类型" width="120">
          <template #default="scope">
            <el-tag
              :type="getFeedbackTypeTag(scope.row.feedbackType)"
              size="small"
            >
              {{ getFeedbackTypeName(scope.row.feedbackType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="urgencyLevel" label="紧急程度" width="100">
          <template #default="scope">
            <el-tag
              :type="getUrgencyTag(scope.row.urgencyLevel)"
              size="small"
            >
              {{ getUrgencyName(scope.row.urgencyLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="内容" min-width="200" show-overflow-tooltip />
        <el-table-column prop="submissionTime" label="提交时间" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag
              :type="getStatusTag(scope.row.status)"
              size="small"
            >
              {{ getStatusName(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="handleFeedback(scope.row)"
            >
              处理
            </el-button>
            <el-button
              size="small"
              type="success"
              :disabled="scope.row.status === 'resolved' || scope.row.status === 'closed'"
              @click="markAsResolved(scope.row)"
            >
              标记解决
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalFeedbacks"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 反馈处理对话框 -->
    <el-dialog
      v-model="feedbackDialogVisible"
      :title="`处理反馈`"
      width="60%"
    >
      <div class="feedback-detail-container">
        <div class="feedback-info">
          <div class="info-item">
            <span class="label">提交用户：</span>
            <span>ID: {{ currentFeedback.userId }}</span>
          </div>
          <div class="info-item">
            <span class="label">提交时间：</span>
            <span>{{ currentFeedback.submissionTime }}</span>
          </div>
          <div class="info-item">
            <span class="label">反馈类型：</span>
            <el-tag :type="getFeedbackTypeTag(currentFeedback.feedbackType)" size="small">
              {{ getFeedbackTypeName(currentFeedback.feedbackType) }}
            </el-tag>
          </div>
          <div class="info-item">
            <span class="label">紧急程度：</span>
            <el-tag :type="getUrgencyTag(currentFeedback.urgencyLevel)" size="small">
              {{ getUrgencyName(currentFeedback.urgencyLevel) }}
            </el-tag>
          </div>
          <div class="info-item">
            <span class="label">当前状态：</span>
            <el-tag :type="getStatusTag(currentFeedback.status)" size="small">
              {{ getStatusName(currentFeedback.status) }}
            </el-tag>
          </div>
        </div>

        <div class="feedback-content">
          <h4>反馈内容：</h4>
          <div class="content-box">{{ currentFeedback.content }}</div>
        </div>

        <div class="feedback-images" v-if="currentFeedback.images && currentFeedback.images.length > 0">
          <h4>附件图片：</h4>
          <div class="image-list">
            <el-image
              v-for="(img, index) in currentFeedback.images"
              :key="index"
              :src="img"
              :preview-src-list="currentFeedback.images"
              fit="cover"
              class="feedback-image"
            />
          </div>
        </div>

        <div class="reply-history" v-if="currentFeedback.replies && currentFeedback.replies.length > 0">
          <h4>回复历史：</h4>
          <div class="reply-list">
            <div
              v-for="(reply, index) in currentFeedback.replies"
              :key="index"
              class="reply-item"
              :class="{ 'admin-reply': reply.isAdmin }"
            >
              <div class="reply-header">
                <span class="reply-user">{{ reply.isAdmin ? '管理员' : currentFeedback.userName }}</span>
                <span class="reply-time">{{ reply.time }}</span>
              </div>
              <div class="reply-content">{{ reply.content }}</div>
            </div>
          </div>
        </div>

        <div class="reply-form">
          <h4>回复：</h4>
          <el-form :model="replyForm">
            <el-form-item>
              <el-input
                v-model="replyForm.content"
                type="textarea"
                :rows="4"
                placeholder="请输入回复内容..."
              />
            </el-form-item>
            <el-form-item>
              <el-select v-model="replyForm.status" placeholder="更新状态">
                <el-option label="保持当前状态" :value="currentFeedback.status" />
                <el-option label="处理中" value="processing" />
                <el-option label="已解决" value="resolved" />
                <el-option label="已关闭" value="closed" />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="feedbackDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReply(currentFeedback,replyForm)">提交回复</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { saveAs } from 'file-saver'
import XLSX from 'xlsx/dist/xlsx.full.min.js'
import { Download, Search } from '@element-plus/icons-vue'
import axios from 'axios'
import { API_BASE_URL } from '@/utils/constants'

// 筛选条件
const urgencyLevel = ref('')
const feedbackType = ref('')
const status = ref('')
const dateRange = ref([])
const viewMode = ref('all')

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const totalFeedbacks = ref(0)

// 表格数据
const loading = ref(false)
const feedbackTableData = ref([])

//数据
const allFeedbacks = ref([])
// 反馈处理对话框
const feedbackDialogVisible = ref(false)
const currentFeedback = ref({})
const replyForm = reactive({
  content: '',
  status: ''
})

// 应用筛选
const applyFilters = () => {
  currentPage.value = 1
  fetchFeedbackData()
}

// 获取反馈数据
const  fetchFeedbackData = async () => {
  loading.value = true
  // 模拟API请求
  // setTimeout(() => {
  try{
    const res = await axios.get(`${API_BASE_URL}/user-feedback/list`)
    console.log(res.data.data)
    allFeedbacks.value = res.data.data

  }catch(err){
    console.log(err)
  }
    
    // 应用筛选
    let filteredFeedbacks = allFeedbacks.value
    
    // 视图模式筛选
    if (viewMode.value !== 'all') {
      filteredFeedbacks = filteredFeedbacks.filter(item => {
        if (viewMode.value === 'pending') {
          return item.status === 'pending' || item.status === 'processing'
        } else if (viewMode.value === 'resolved') {
          return item.status === 'resolved' || item.status === 'closed'
        }
        return true
      })
    }
    
    // 紧急程度筛选
    if (urgencyLevel.value) {
      filteredFeedbacks = filteredFeedbacks.filter(item => item.urgencyLevel === urgencyLevel.value)
    }
    
    // 反馈类型筛选
    if (feedbackType.value) {
      filteredFeedbacks = filteredFeedbacks.filter(item => item.feedbackType === feedbackType.value)
    }
    
    // 状态筛选
    if (status.value) {
      filteredFeedbacks = filteredFeedbacks.filter(item => item.status === status.value)
    }
    
    // 日期筛选
    if (dateRange.value && dateRange.value.length === 2) {
      const startDate = new Date(dateRange.value[0])
      const endDate = new Date(dateRange.value[1])
      endDate.setHours(23, 59, 59, 999)
      filteredFeedbacks = filteredFeedbacks.filter(item => {
        const itemDate = new Date(item.submissionTime)
        return itemDate >= startDate && itemDate <= endDate
      })
    }

    // 分页处理
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    totalFeedbacks.value = filteredFeedbacks.length
    feedbackTableData.value = filteredFeedbacks.slice(start, end)
    loading.value = false
  // }, 500)
}

// 导出数据
const exportFeedback = () => {
  const exportData = feedbackTableData.value.map(item => ({
    ID: item.id,
    用户ID: item.userId,
    用户姓名: item.userName,
    反馈类型: getFeedbackTypeName(item.type),
    紧急程度: getUrgencyName(item.urgency),
    标题: item.title,
    提交时间: item.createTime,
    状态: getStatusName(item.status),
    解决时间: item.resolutionTime || '-' // 添加解决时间字段
  }))

  const ws = XLSX.utils.json_to_sheet(exportData)
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '反馈数据')
  const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
  saveAs(new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }), '反馈数据.xlsx')
}

// 处理反馈
const handleFeedback = (row) => {
  currentFeedback.value = { ...row }
  replyForm.status = row.status
  feedbackDialogVisible.value = true
}

// 修改标记解决方法
const markAsResolved = async (row) => {
  try {
    // 调用后端API更新状态（示例）
    const res = await axios.put(`${API_BASE_URL}/user-feedback/update/${row.feedbackId}`, {
      ...row,
      status: 'resolved',
      resolutionTime: new Date().toISOString() // 更新解决时间
    })

    if (res.data.code === 1) {
      // 本地数据同步更新
      const index = feedbackTableData.value.findIndex(
        item => item.feedbackId === row.feedbackId
      )
      if (index !== -1) {
        feedbackTableData.value[index].status = 'resolved'
        feedbackTableData.value[index].resolutionTime = new Date().toISOString()
        ElMessage.success('状态已更新为已解决')
      }
      fetchFeedbackData();
    }
  } catch (error) {
    ElMessage.error('状态更新失败')
    console.error(error)
  }
}

// 修改后的submitReply方法
const submitReply = async (row,data) => {
  if (!replyForm.content.trim()) {
    ElMessage.warning('请输入回复内容')
    return
  }

  try {
    // 构造完整的回复数据
    // 构造完整的回复数据
    // const replyData = {
    //   feedbackId: currentFeedback.value.feedbackId, // 使用接口定义的feedbackId字段
    //   content: replyForm.content,
    //   status: replyForm.status,
    //   updateTime: new Date().toISOString(), // 添加更新时间字段
    //   adminId: 1, // 管理员ID（根据实际情况获取）
    //   replyType: 'admin_reply' // 回复类型
    // }

    // 调用后端API提交回复
    // 调用后端API提交回复


    const res = await axios.put(`${API_BASE_URL}/user-feedback/update/${row.feedbackId}`, {
      ...row,
      processingNotes: data.content,
      status:data.status,
      resolutionTime: new Date().toISOString() // 更新解决时间
    })
    if (res.data.code === 1) {
      // 本地数据同步更新
      const index = feedbackTableData.value.findIndex(
        item => item.feedbackId === row.feedbackId
      )
      if (index !== -1) {
        feedbackTableData.value[index].status = data.status
        feedbackTableData.value[index].resolutionTime = new Date().toISOString()
        ElMessage.success('状态已更新')
      }
      fetchFeedbackData();
    }
  } catch (error) {
    ElMessage.error('提交失败，请检查网络连接')
    console.error('回复提交错误:', error)
    
    // 网络错误时尝试重新拉取数据
    if (error.response?.status !== 200) {
      await fetchFeedbackData()
    }
  }
}

// 工具函数
const getFeedbackTypeTag = (type) => {
  const tags = {
    system: 'danger',
    content: 'warning',
    operation: 'info',
    device: '',
    other: 'info'
  }
  return tags[type] || 'info'
}

const getFeedbackTypeName = (type) => {
  const names = {
    system: '系统问题',
    content: '内容建议',
    operation: '操作问题',
    device: '设备问题',
    other: '其他'
  }
  return names[type] || '未知'
}

const getUrgencyTag = (urgency) => {
  const tags = {
    high: 'danger',
    medium: 'warning',
    low: 'info'
  }
  return tags[urgency] || 'info'
}

const getUrgencyName = (urgency) => {
  const names = {
    high: '紧急',
    medium: '中等',
    low: '普通'
  }
  return names[urgency] || '未知'
}

const getStatusTag = (status) => {
  const tags = {
    pending: 'info',
    processing: 'warning',
    resolved: 'success',
    closed: ''
  }
  return tags[status] || 'info'
}

const getStatusName = (status) => {
  const names = {
    pending: '待处理',
    processing: '处理中',
    resolved: '已解决',
    closed: '已关闭'
  }
  return names[status] || '未知'
}

// 分页处理函数
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchFeedbackData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchFeedbackData()
}

// 监听视图模式变化
watch(viewMode, () => {
  currentPage.value = 1
  fetchFeedbackData()
})

// 模拟数据
const mockFeedbackData = () => {
  return Array.from({ length: 50 }, (_, index) => ({
    id: index + 1,
    userId: Math.floor(Math.random() * 10000),
    type: ['system', 'content', 'operation', 'device', 'other'][Math.floor(Math.random() * 5)],
    urgency: ['high', 'medium', 'low'][Math.floor(Math.random() * 3)],
    content: `这是反馈内容 ${index + 1}，包含了用户的具体问题描述...`,
    resolutionTime: new Date(Date.now() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000).toLocaleString(),
    status: ['pending', 'processing', 'resolved', 'closed'][Math.floor(Math.random() * 4)],
  }))
}

// 初始化
onMounted(() => {
  fetchFeedbackData()
})
</script>